const { Controller } = require("egg");
const checkUserAgent = require("../util/checkUserAgent");

class ChapterController extends Controller {
    //新增章
    async create() {
            try {
                const body = this.ctx.request.body
                body.orderby = Number(body.orderby)
                const a = await this.ctx.service.chapter.addChapter(body)
                this.ctx.body = {
                    code: 20000,
                    message: true
                }
            } catch (error) {
                this.ctx.body = {
                    code: 50000,
                    message: false
                }
            }
        }
        //获取章
    async index() {
            try {
                const book_id = this.ctx.request.query.book_id
                const ChapterList = await this.ctx.service.chapter.getChapter(book_id)
                this.ctx.body = {
                    code: 20000,
                    message: true,
                    chapterList: ChapterList
                }
            } catch (error) {
                this.ctx.body = {
                    code: 50000,
                    message: false
                }
            }
        }
        //删除章
    async destroy() {
            try {
                const id = this.ctx.params.id
                await this.ctx.service.chapter.deleteChapter(id)
                this.ctx.body = {
                    code: 20000,
                    message: true,
                }
            } catch (error) {
                this.ctx.body = {
                    code: 50000,
                    message: false
                }
            }
        }
        //更新章
    async update() {
        try {
            const id = this.ctx.params.id
            const body = this.ctx.request.body
            await this.ctx.service.chapter.updateChapter(id, body)
            this.ctx.body = {
                code: 20000,
                message: true,
            }
        } catch (error) {
            this.ctx.body = {
                code: 50000,
                message: false
            }
        }
    }
    async getChapter(){
        const {ctx} = this;
        const book_id = ctx.params.id;
        const ua = checkUserAgent(ctx.header['user-agent'])
        const chapterList =  await this.ctx.service.website.getChapterPage(book_id)
        if(ua){
            await ctx.render("pc/chapterDetail.html",chapterList)
        }else{
            await ctx.render("mobile/chapterDetail.html",chapterList)

        }
    }
}
module.exports = ChapterController